import { CloseCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import { message, Modal, Popover } from 'antd'
import classNames from 'classnames'
import { memo, useEffect, useRef, useState } from 'react'
import { NavigateFunction } from 'react-router-dom'
import { useAppDispatch, useAppSelector } from 'store/hook'
import { addCommonSign, deleteSign } from 'store/slices/signSlice'
import styles from './index.module.scss'
type Props = {
  signInfo: Sign
  className?: string
  navigate?: NavigateFunction
}

function SignItem({ signInfo, className, navigate }: Props) {
  const [isModalOpen, setIsModalOpen] = useState(false)
  const dispatch = useAppDispatch()
  const timerId = useRef(-1)
  const { editMode, onlineStatus } = useAppSelector(state => state.system)

  // 复制符号
  const handleCopySign = (type?: string) => {
    window.clearTimeout(timerId.current)
    timerId.current = window.setTimeout(() => {
      let copyContent = ''
      // type 为 'i' 时生成 <i> 标签
      if (type === 'i') {
        copyContent = `<i class="${signInfo.signName}">${signInfo.sign}</i>`
      } else {
        copyContent = signInfo.sign
      }

      // 安全域下使用 navigator.clipboard 提升效率
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(copyContent).then(() => {
          message.success(`已成功复制${type === 'i' ? '标签 ' : '符号 '} ${copyContent}`)
        })
      } else {
        // 非安全域使用 document.execCommand('copy')
        // 创建text area
        const textArea = document.createElement('textarea')
        textArea.value = copyContent
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()
        document.execCommand('copy')
        textArea.remove()
        message.success(`已成功复制${type === 'i' ? '标签 ' : '符号 '} ${copyContent}`)
      }

      dispatch(addCommonSign(signInfo))
    }, 300)
  }

  // 显示符号详情
  const handleShowDetail = () => {
    window.clearTimeout(timerId.current)
    setIsModalOpen(true)
  }

  // 清理延时器
  useEffect(() => {
    return () => {
      window.clearTimeout(timerId.current)
    }
  })

  // 删除自定义符号
  const handleDeleteSign = () => {
    Modal.confirm({
      title: '删除操作',
      icon: <ExclamationCircleOutlined />,
      content: '您确定要删除该符号吗？',
      async onOk() {
        await dispatch(deleteSign(signInfo.id))
        navigate!('/')
        // window.location.href = process.env.PUBLIC_URL as string
        message.success(`删除成功！`)
      }
    })
  }

  return (
    <span className={styles['sign-item']}>
      <Popover
        content={
          <>
            <i
              style={{ userSelect: 'none', cursor: 'pointer', fontStyle: 'normal', fontWeight: 'bold', color: signInfo.categoryId ? '#000000' : '#e21918' }}
              hidden={editMode !== 'edit'}
              onClick={() => {
                if (!signInfo.categoryId && !onlineStatus) {
                  //  无 categoryId，则为系统自带符号，需要连接服务器编辑
                  return message.error('未连接服务器，无法编辑系统自带符号！', 1)
                }
                navigate!(`/CustomSign?id=${signInfo.id}`)
              }}>
              Edit
            </i>
            <br hidden={editMode !== 'edit'} />
            <i style={{ userSelect: 'none', cursor: 'pointer', fontStyle: 'normal', fontWeight: 'bold' }} onClick={() => handleCopySign('i')}>
              &lt;i&gt;
            </i>
          </>
        }>
        <i className={classNames('sign', signInfo.signName, className)} onClick={() => handleCopySign()} onDoubleClick={handleShowDetail}>
          {signInfo.sign}
          {signInfo.categoryId ? (
            <CloseCircleOutlined
              onClick={e => {
                e.stopPropagation()
                handleDeleteSign()
              }}
            />
          ) : null}
        </i>
      </Popover>
      <Modal title={'『 ' + signInfo.sign + ' 』的历史背景'} open={isModalOpen} onOk={() => setIsModalOpen(false)} onCancel={() => setIsModalOpen(false)}>
        {signInfo.sign === '©' ? (
          <>
            <h2>概念</h2>
            <p>C 外加一圆圈，表示Copyright Notice,即版权标记。为《世界版权公约》中版权保留的标记。</p>
            <p>© 是 Copyright 的标志，意思为受版权保护。</p>
            <p>
              版权保护，又称著作权，最终目的不是“如何防止使用”，而是“如何控制使用”，版权法的实质是一种控制作品使用的机制。中国因特网版权保护的关键是在促进网络发展和保护著作权人利益间寻求平衡，当务之急是尽快完善这方面的立法。
            </p>
          </>
        ) : (
          <p>暂无数据！</p>
        )}
      </Modal>
    </span>
  )
}

export default memo(SignItem)
